﻿$(function () {
    $("#submit").click(function () {
        Submit();
    });

    $("#body").keypress(function (event) {
        if (event.which == '13') {
            Submit();
        }
    });

    $("#TypeID").change(function () {
        Ajax({
            url: "/Classifieds/GetCategoriesByType",
            data: JSON.stringify({ typeId: $("#TypeID").val() }),
            success: function (data) {
                $("#CategoryID option:not(:first)").remove();
                for (var i in data) {
                    $("#CategoryID").append("<option value=\"" + data[i].ID + "\">" + data[i].Name + "</option>");
                }
            }
        });
    });

    $("#Member").autocomplete({
        source: "/Membership/GetMembersBySearch",
        minLength: 0,
        focus: function (event, ui) {
            $("#Member").val(ui.item.Email);
            return false;
        },
        select: function (event, ui) {
            $("#Member").val(ui.item.Email);
            $("#MemberID").val(ui.item.ID);
            return false;
        }
    }).data("autocomplete")._renderItem = function (ul, item) {
        return $("<li></li>")
				.data("item.autocomplete", item)
				.append("<a>" + item.FirstName + " " + item.LastName + " (" + item.Email + ")</a>")
				.appendTo(ul);
    };
});

function Submit() {

    $("#submit").hide();
    var input = {
        ID: $("#id").val(),
        CategoryID: $("#CategoryID").val(),
        MemberID: $("#MemberID").val(),
        StatusID: $("input[name='Status']:checked").val(),
        Title: $("#Title").val(),
        Price: $("#Price").val(),
        Location: $("#Location").val(),
        ReplyTo: $("#ReplyTo").val(),
        Description: $("#Description").val(),
        ExpiresOn: $("#ExpiresOn").val()
    };
    
    Ajax({
        url: "/Classifieds/Save",
        data: JSON.stringify(input),
        success: function (data) {
            if (data.IsValid == false) {
                ShowValidationErrors(data, { "MemberID": "Member" });
            } else if (data.IsSaved == true) {
                location.href = "/Classifieds?msg=1";
            }
        },
        complete: function () {
            $("#submit").show();
        }
    });
}